package com.dhcc.wb.util;

import java.util.Date;
import java.util.List;

import org.json.JSONObject;

import com.dhcc.wb.gongzhonghao.GzhDao;
import com.dhcc.wb.gongzhonghao.GzhModel;


/**
 * @author wangbin
 * @datetime 2019年10月22日
 * @todo TODO
 */
public class TokenUtil {

	//系统初始化
	public static void chushihua(){
		GzhDao dao = new GzhDao();
		List<GzhModel> gzhlist = dao.getAll();
		
		if(gzhlist != null && gzhlist.size()>0){
			for(GzhModel ent : gzhlist){
					String tokenjson = getToken(ent.getAppid(), ent.getSecret());
					updateToken(ent.getGzhid(), tokenjson);
			}
		}
	} 

	
	
     
	//通过URL得到公众号token
	public static String getToken(String appid,String secret) {
		 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
		 String json = HttpUtil.getContent(url);
		 return json;
	}
	
	//更新token
	public static void updateToken(String gzhid,String tokenjson) {
		GzhDao dao = new GzhDao();
		Date day = new Date();
		Long creattime = day.getTime();
		JSONObject jsona = new JSONObject(tokenjson);
		if(jsona.has("access_token")){
			String access_token = jsona.getString("access_token");
			Integer expire_in = jsona.getInt("expires_in");
			dao.updateGzh(gzhid, access_token, creattime, creattime+expire_in*1000, expire_in);
		}
		
	}
	
	
	
	
	//通过数据库查询公众号token
	public static String getToken(String gzhid) {
		String token = "";
		GzhDao dao = new GzhDao();
		GzhModel ent = dao.queryqiye_result(gzhid);
		Date dd = new Date();
		if(null == ent.getDaoqitime() || dd.getTime()>ent.getDaoqitime()){//token过期了
			String tokenjson = getToken(ent.getAppid(), ent.getSecret());
			JSONObject jsona = new JSONObject(tokenjson);
			if(jsona.has("access_token")){
				updateToken(gzhid, tokenjson);
				token = jsona.getString("access_token");
			}
		}else{//token没有过期
			token = ent.getAccess_token();
		}
		return token;
	}
	
	public static void main(String[] args) {
		String aa = getToken("00bd81a7-d6af-42dd-b1c6-637fbf4159cf");
		System.out.println("=========="+aa);
	}
	
	
}
